package com.csyf.manager.channel.pddPay;

import com.alibaba.fastjson.JSONObject;
import com.csyf.manager.channel.base.PaymentVo;
import com.csyf.manager.channel.base.TrandeVo;
import com.csyf.manager.common.CommonConst;
import com.csyf.manager.entity.SysAgentChannel;
import com.csyf.manager.exception.ApiValidateException;
import com.csyf.manager.service.impl.RedisService;
import com.csyf.manager.utils.HttpHelper;
import com.csyf.manager.utils.NumberHelpler;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * @Auther: casper
 * @Date: 2019/12/2 15:10
 * @Description: 拼多多
 */
@Slf4j
@Service
public class PddPayBiz {

    @Autowired
    private RedisService redisService;

    public String dopay(TrandeVo vo, String srcmchId) throws Exception {
        String channelStr = redisService.getSrcChannelInfo(vo.getMch_id(), srcmchId);
        SysAgentChannel sysAgentChannel = new Gson().fromJson(channelStr, SysAgentChannel.class);

        Map<String, String> params = new TreeMap<>();
        params.put("type", sysAgentChannel.getTermialId());
        params.put("total", NumberHelpler.cent2money(vo.getTotal_fee()).toString());
        params.put("api_order_sn", vo.getOut_trade_no());
        params.put("notify_url", sysAgentChannel.getNotifyUrl());
        params.put("client_id", sysAgentChannel.getMerchantNo());
        params.put("timestamp", System.currentTimeMillis() + "");

        String str = map2signkey(params);
        String signStr = DigestUtils.md5Hex(sysAgentChannel.getSignKey() + str + sysAgentChannel.getSignKey()).toUpperCase();

        params.put("sign", signStr);

        log.info("[{}]拼多多请求上游参数：{}", vo.getOut_trade_no(), params);
        String resultStr = HttpHelper.doPostForm("http://103.104.105.129/index/api/order", params, CommonConst.UTF8);
        log.info("[{}]拼多多上游响应报文：{}", vo.getOut_trade_no(), resultStr);

        String qr_url = null;
        JSONObject jsonObj = JSONObject.parseObject(resultStr);

        String msg = jsonObj.getString("msg");

        if (resultStr.contains("error_code")) {
            int error_code = jsonObj.getInteger("error_code");
            throw new ApiValidateException(error_code + "|" + msg);
        }

        int code = jsonObj.getInteger("code");
        if (code==200) {
            String data = jsonObj.getString("data");
            Map<String, String> map = new Gson().fromJson(data, Map.class);
            qr_url = map.get("qr_url");
        }
        return qr_url;
    }


    public static String map2signkey(Map<String, String> object) {
        Set<Map.Entry<String, String>> entrySet = object.entrySet();
        ArrayList<String> arrayList = new ArrayList<>();
        for (Map.Entry<String, String> entry : entrySet) {
            if ("sign".equals(entry.getKey())) {
                continue;
            }
            if (null == entry.getValue() || entry.getValue().length() <= 0) {
                continue;
            }
            arrayList.add(entry.getKey() + entry.getValue());
        }
        String join = StringUtils.join(arrayList, "");
        log.info("签名字符串:{}", join);
        return join;
    }

    /**
     * 代付
     * @param vo
     * @param srcMchId
     * @return
     */
    public Map<String, String> dodfpay(PaymentVo vo, String srcMchId) {
        Map<String, String> respMap = new TreeMap<>();
        return respMap;
    }



}
